﻿var allDepData = "";
$(function () {
    $.ajax({
        type: "GET",
        url: "/Sys/Department/GetAllListToJson?_t=" + new Date().getTime(),
        success: function (data) {
            allDepData = data;
            loadDepartment();
        }
    });

    $("#btnAdd").click(function () { add(); });
    $("#btnDelete").click(function () { deleteMulti(); });
    $("#btnSave").click(function () {
        //验证表单
        var departmentId = $("#DepartmentId").val();
        if ($.trim(departmentId) == "") {
            str = '部门不能为空';
            layer.tips(str, "#btnSave");
            $("#DepartmentId").focus();
            return;
        }

        save();
    });
    $("#checkAll").click(function () { checkAll(this) });
    
    
    loadTables(1);
   
    uploadPic();

});

//加载列表数据
function loadTables(pageindex) {
    $("#tableBody").html("");
    $("#checkAll").prop("checked", false);
    $.ajax({
        type: "GET",
        url: "/Gzh/Police/GetPagedListToJson?pageindex=" + pageindex + "&_t=" + new Date().getTime(),
        success: function (data) {
            $.each(data.rows, function (i, item) {
                var tr = "<tr>";
                tr += "<td align='center'><input type='checkbox' class='checkboxs' value='" + item.id + "'/></td>";
                tr += "<td>" + item.name + "</td>";
                tr += "<td>" + item.position + "</td>";
                tr += "<td>" + item.tel + "</td>";
                tr += "<td>" + (item.isGood == false ? "否" : "展示") + "</td>";
                tr += "<td><button class='btn btn-info btn-xs' href='javascript:;' onclick='edit(\"" + item.id + "\")'><i class='fa fa-edit'></i> 编辑 </button> <button class='btn btn-danger btn-xs' href='javascript:;' onclick='deleteSingle(\"" + item.id + "\")'><i class='fa fa-trash-o'></i> 删除 </button> </td>"
                tr += "</tr>";
                $("#tableBody").append(tr);
            })
            var elment = $("#grid_paging_part"); //分页插件的容器id
            if (data.rowCount > 0) {
                var options = { //分页插件配置项
                    bootstrapMajorVersion: 3,
                    currentPage: pageindex, //当前页
                    numberOfPages: data.rowsCount, //总数
                    totalPages: data.pageCount, //总页数
                    onPageChanged: function (event, oldPage, newPage) { //页面切换事件
                        loadTables(newPage);
                    }
                }
                elment.bootstrapPaginator(options); //分页插件初始化
            }
           
        }
    })
}

function loadDepartment() {
    $("#DepartmentId").html("");
    var option = "";
    $.each(allDepData, function (i, item) {
        if (item.parentId == 4) {
            option += "<option value='" + item.id + "'>" + item.name + "</option>"
        }
    })
    $("#DepartmentId").append(option);
}


function changeDepartmentId(parentId)
{
    //清空二级菜单选项  
    $("#SecDepartmentId").html("");
    var option = "";
    if (parentId == 0) return;    

    $.each(allDepData, function (i,item) {
        if (item.parentId == parentId) {
            option += "<option value='" + item.id + "'>" + item.name + "</option>"
        }
    });
    $("#SecDepartmentId").append(option);
 
}
//全选
function checkAll(obj) {
    $(".checkboxs").each(function () {
        if (obj.checked == true) {
            $(this).prop("checked", true)

        }
        if (obj.checked == false) {
            $(this).prop("checked", false)
        }
    });
};
//新增
function add() {
    $("#img").html("<div id='img'></div> ");    //此处不进行清空，会显示上次的效果

    $("#Id").val(0);
    $("#Name").val("");
    $("#Position").val("社区民警");
    $("#Tel").val("");
    $("#PicPath").val("police.jpg");
    $("#DepartmentId").val("");
    $("#SecDepartmentId").val("");
    $("#Description").val("");
    $("#Sort").val("0");
    $("#IsGood").prop("checked", false);

    $("#Title").text("新增");
    //弹出新增窗体
    $("#editModal").modal("show");
};
//编辑
function edit(id) {
    $.ajax({
        type: "Get",
        url: "/Gzh/Police/GetByIdToJson?id=" + id + "&_t=" + new Date().getTime(),
        success: function (data) {
            $("#CreatedBy").val(data.createdBy);
            $("#CreatedOn").val(data.createdOn);

            $("#Id").val(data.id);
            $("#Name").val(data.name);
            $("#Position").val(data.position);
            $("#Tel").val(data.tel);
            $("#PicPath").val(data.picPath); 
            $("#DepartmentId").val(data.departmentId);
            changeDepartmentId(data.departmentId);
            $("#SecDepartmentId").val(data.secDepartmentId);
            $("#Description").val(data.remarks);
            $("#Sort").val(data.sortIndex);
            $("#IsGood").prop("checked", data.isGood);
            
            $("#img").html("<img src='/UploadFiles/" + $('#PicPath').val() + "' style='width:100px;'>");

            $("#Title").text("编辑")
            $("#editModal").modal("show");
        }
    })
};
//保存
function save() {

    var postData = {
        "CreatedBy": $("#CreatedBy").val(),
        "CreatedOn": $("#CreatedOn").val(),

        "Id": $("#Id").val(),
        "Name": $("#Name").val(),
        "Position":$("#Position").val(),
        "Tel":$("#Tel").val(),
        "PicPath":$("#PicPath").val(),
        "DepartmentId":$("#DepartmentId").val(),
        "SecDepartmentId":$("#SecDepartmentId").val(),
        "Remarks":$("#Description").val(),
        "SortIndex": $("#Sort").val(),
        "IsGood": $("#IsGood").prop('checked')
    };
    $.ajax({
        type: "Post",
        url: "/Gzh/Police/AddOrModify",
        data: postData,
        success: function (data) {
            if (data.result == "Success") {
                loadTables(1)
                $("#editModal").modal("hide");
            } else {
                layer.tips(data.message, "#btnSave");
            };
        }
    });
}

//批量删除
function deleteMulti() {
    var ids = "";
    $(".checkboxs").each(function () {
        if ($(this).prop("checked") == true) {
            ids += $(this).val() + ","
        }
    });
    ids = ids.substring(0, ids.length - 1);
    if (ids.length == 0) {
        layer.alert("请选择要删除的记录。");
        return;
    };
    //询问框
    layer.confirm("您确认删除选定的记录吗？", {
        btn: ["确定", "取消"]
    }, function () {
        var sendData = { "ids": ids };
        $.ajax({
            type: "Post",
            url: "/Police/DeleteMutiByIds",
            data: sendData,
            success: function (data) {
                if (data.result == "Success") {
                    loadTables(1);
                    layer.closeAll();
                }
                else {
                    layer.alert("删除失败！");
                }
            }
        });
    });
};
//删除单条数据
function deleteSingle(id) {
    layer.confirm("您确认删除选定的记录吗？", {
        btn: ["确定", "取消"]
    }, function () {
        $.ajax({
            type: "POST",
            url: "/Police/DeleteById",
            data: { "id": id },
            success: function (data) {
                if (data.result == "Success") {
                    loadTables(1);
                    layer.closeAll();
                }
                else {
                    layer.alert("删除失败！");
                }
            }
        })
    });
};

//图片上传
function uploadPic() {
    //参考https://github.com/think2011/localResizeIMG/wiki/2.-%E5%8F%82%E6%95%B0%E6%96%87%E6%A1%A3
    $('#capture').on('change', function () {
        lrz(this.files[0], { width: 600 })
            .then(function (rst) {
                rst.formData.append('fileLen', rst.fileLen);
                $.ajax({
                    type: "POST",
                    url: "/Picture/UploadFilesAjax",
                    contentType: false,
                    processData: false,
                    data: rst.formData,
                    success: function (item) {
                        // alert("上传成功！");
                        $("#PicPath").val(item);

                        $("#img").html("<img src='/UploadFiles/" + $('#PicPath').val() + "' style='width:100px;'>");
                    },
                    error: function () {
                        alert("上传失败!");
                    }
                });
            })
            .catch(function (err) {
                // 处理失败会执行
            })
            .always(function () {
                // 不管是成功失败，都会执行
            });
    });
}